
package dao;

import org.hibernate.Session;
import org.hibernate.Transaction;
import model.Aluno;
import org.hibernate.Query;
import connection.connectionFactory;
import java.util.ArrayList;
import java.util.List;

public class AlunoDao {
        
    Session session;
    Transaction tx; 
    List<Aluno> listaAluno = new ArrayList<Aluno>();
    
    public void salvar(Aluno aluno)
    {
      try
      {
          session = new connectionFactory().getSessionFactory();
          tx =  session.beginTransaction();
          session.save(aluno);
          tx.commit();
          session.close();
            
      }
      catch(Exception e)
      {
           e.printStackTrace();
           tx.rollback();
           session.close();
      }
    } 
    
    public void alterar(Aluno aluno)
    {
      try
      {
          session = new connectionFactory().getSessionFactory();
          tx =  session.beginTransaction();
          session.update(aluno);
          tx.commit();
          session.close();
            
      }
      catch(Exception e)
      {
           e.printStackTrace();
           tx.rollback();
           session.close();
      }
    }  
    
    public void excluir(Aluno aluno)
    {
      try
      {
          session = new connectionFactory().getSessionFactory();
          tx =  session.beginTransaction();
          session.delete(aluno);
          tx.commit();
          session.close();
            
      }
      catch(Exception e)
      {
           e.printStackTrace();
           tx.rollback();
           session.close();
      }
    } 
    
    public List<Aluno> listar()
    {
      try
      {
          session = new connectionFactory().getSessionFactory();
          listaAluno = session.createCriteria(Aluno.class).list();
          
      }
      catch(Exception e)
      {
           e.printStackTrace();
           session.close();
      }
      
      return listaAluno;
    } 
    
    public Aluno consultarPorId(int codigo)
    {
        session = new connectionFactory().getSessionFactory();
        Query query = session.createSQLQuery("SELECT * FROM aluno WHERE alunid = "+codigo+"").addEntity(Aluno.class);
        listaAluno = query.list();
        
        session.close();
        return listaAluno.get(0); 
    }
}
